server {
    listen 8080;
    
    set_by_lua_block $user_id {
        return "zhangsan"
    }

    # token
    set $token "";
    
    # timestamp
    set_by_lua_file $timestamp seckill-nginx/lua/set_common_var.lua;

    # 调用顺序1
    # 活动数据查询 
    location /activity/activityData {
        # limit_req zone=limit_by_user nodelay;
        access_by_lua_file seckill-nginx/lua/black_list_validate.lua;
        
        proxy_pass http://backend;
       
        header_filter_by_lua_block {
            local timestamp = ngx.time()
            ngx.header["token"] = ngx.md5(timestamp..1)
            ngx.header["timestamp"] = timestamp
            ngx.header["Access-Control-Expose-Headers"] = "token"
            ngx.header["Access-Control-Expose-Headers"] = "timestamp"
        }
    }

    # 商详情页
    location /buy {
        proxy_pass http://backend;
    }

    # 调用顺序2；需校验 seq 1
    # 结算页
    location /settlement {
        set $except_seq 1;
        rewrite_by_lua_file seckill-nginx/lua/token_validate.lua;
        
        proxy_pass http://backend;
        error_page 403 error.html;
    }

    # 调用顺序2：需校验 seq 1
    # 结算页 token
    location /settlement/token {
        set $except_seq 1;
        rewrite_by_lua_file seckill-nginx/lua/token_validate.lua;
        
        default_type application/json;
        content_by_lua_block {
            json = require "cjson"
            local t = ngx.time()
            local result = {}
            result["token"] = ngx.md5(t..2)
            result["timestamp"] = t
            ngx.say(json.encode(result))
        }
        error_page 403 @json_error;
    } 

    # 调用顺序3：需校验 seq2
    # 结算页提交订单
    location /settlement/submitOrder {
        set $except_seq 2;
        rewrite_by_lua_file seckill-nginx/lua/token_validate.lua;
        
        proxy_pass http://backend;
        error_page 403 @json_error;
    }

    # 以下是非秒杀系统的路径

    # 后台-商品消息查询页、商品数据接口
    location /product {
        proxy_pass http://backend;
    }

    # 后台-活动管页、活动管理接口
    location /activity {
        proxy_pass http://backend;
    }

    # 支付页
    location /pay {
        proxy_pass http://backend;
    }

    # 抢购失败页
    location /fail {
        proxy_pass http://backend;
    }

    # 错误页
    location = /error.html {
        root seckill-nginx/html;
    }

    # 以 @ 开头的是内部接口，外部无法访问
    location @json_error {
        default_type application/json;
        return 200 '{"code": 2, "message": "令牌失效"}';
    }

    # js
    location /js {
        proxy_pass http://backend;
    }

    # rateLimiter AOP 测试
    location /rateLimiter {
        proxy_pass http://backend;
    }
}
